import {computed, ref} from "vue";
import {defineStore} from 'pinia';
import {getIndustryDynamicAPI, getPlantQuarantineAPI} from "../../api/allAPI";
import {dynamicsItem} from "../../api/req";

export const useDynamicsStore = defineStore('DynamicsStore', () => {
    const dynamicsSets = ref<dynamicsItem[]>([]);
    const loading = ref<boolean>(false);
    const dynamicsPage = ref({
        currentPage: 1,
        total: 0,
        pageSize: 10,
        showSizePicker: true,
        pageSizes: Array.from({ length: 200 }, (_, index) => index + 1),
    });

    const updateDynamicsSets = async () => {
        loading.value = true;
        const req = {
            pageNo: dynamicsPage.value.currentPage,
            pageSize: dynamicsPage.value.pageSize,
        };

        const res = await getIndustryDynamicAPI(req);
        const { data, meta } = res.data;

        dynamicsSets.value = data.map((item: any) => ({
            id: item.id,
            title: item.attributes.title,
            time: item.attributes.time
        }));
        dynamicsPage.value.total = meta.pagination.total
        loading.value = false;
    };

    // 设置分页信息
    const setDynamicsSetsPage = (page?: number) => {
        if (page) dynamicsPage.value.currentPage = page;
    };

    const getDynamicsSets = computed(() => {
        return dynamicsSets.value;
    });

    const getPlantPage = computed(() => {
        return dynamicsPage.value;
    });

    const pagination = computed(() => ({
        current: dynamicsPage.value.currentPage,
        total: dynamicsPage.value.total,
        pageSize: dynamicsPage.value.pageSize,
        onChange: (page: number) => {
            setDynamicsSetsPage(page);
            updateDynamicsSets().then()
        },
    }));

    const getDynamicsLoading = computed(() => {
        return loading.value;
    });

    return {
        updateDynamicsSets,
        getDynamicsSets,
        setDynamicsSetsPage,
        getPlantPage,
        pagination,
        getDynamicsLoading
    }
})